﻿using CIS.DB;
using CIS.Web.Common;
using CIS.Web.Models;
using CIS.Web.Properties;
using System;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace CIS.Web.Controllers
{
	[AllowAnonymous]
	[RoutePrefix("Register")]
	public class RegisterController : BaseDbController
	{
		public ActionResult Index()
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName);

			return View();
		}

		public ActionResult ShowPrivacy()
		{
			return View();
		}

		public ActionResult ShowPrivacyEN()
		{
			return View();
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		public async Task<JsonResult> Create(SysUserMasterModel model)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName);

			var result = await DbContext.SysUserMaster.AsNoTracking()
					.AnyAsync(x => x.UserName == model.UserName || x.Mail == model.Mail);

			if (result)
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(
						string.Format(Resources.MsgRecordExist, Resources.LogsTypeUser)),
						JsonRequestBehavior.AllowGet);
			}

			if (model.HeadImgFile != null)
			{
				if (model.HeadImgFile.ContentLength > ConstValues.PicMaxLength)
				{
					string errorMessage = Resources.MsgPicOverflowError;
					return JsonCamelCase(Utility.CreateFailJsonResult(errorMessage),
						JsonRequestBehavior.AllowGet);
				}

				string folder = ConstValues.UserHeadImg;
				string pfolder = Server.MapPath(ConstValues.UserHeadImg);
				string fileName = ConstValues.TableId.SysUserMaster + ConstValues.strHyphen +
						DateTime.Now.ToString("yyyyMMdd") + ConstValues.strHyphen +
						Utility.GetRandom() + Path.GetExtension(model.HeadImgFile.FileName);
				model.HeadImgFilePath = Path.Combine(folder, fileName);
				var saveFileTask = Task.Run(() =>
				{
					string pFullPath = Path.Combine(pfolder, fileName);
					if (!Directory.Exists(pfolder))
					{
						Directory.CreateDirectory(pfolder);
					}
					model.HeadImgFile.SaveAs(pFullPath);
				});
				Task.WaitAll(saveFileTask);
			}

			var newId = Utility.GetTableId(ConstValues.TableName.SysUserMaster);

			using (var transaction = DbContext.Database.BeginTransaction())
			{
				var career = string.Join(ConstValues.strSemicolon, model.Career);
				var ocisCode = string.Join(ConstValues.strSemicolon, model.OcisCode);

				var language = model.Country == 7 ? ConstValues.Language.Cn : ConstValues.Language.En;

				var sysUserMaster = new SysUserMaster
				{
					ID = newId,
					UserName = model.UserName?.Trim(),
					Mail = model.Mail?.Trim(),
					Password = StringExtension.Encrypt(model.Password?.Trim()),
					HeadImg = model.HeadImgFilePath?.Trim(),
					Call = model.Call,
					FamilyName = model.FamilyName?.Trim(),
					FirstName = model.FirstName?.Trim(),
					FullName = !string.IsNullOrEmpty(model.FullName) ? model.FullName?.Trim() :
							Utility.SetFullName(model.FamilyName?.Trim(), model.FirstName?.Trim(),
							language),
					Gender = model.Gender == 1 ? true : false,
					Birthday = model.Birthday,
					Degree = model.Degree,
					Affiliation = model.Affiliation?.Trim(),
					Department = model.Department?.Trim(),
					Address = model.Address?.Trim(),
					ZipCode = model.ZipCode?.Trim(),
					Country = model.Country,
					StateStr = model.State,
					CityStr = model.City,
					Mobile = model.Mobile?.Trim(),
					Telephone = model.Telephone?.Trim(),
					Career = career,
					OcisCode = ocisCode,
					Status = ConstValues.Status.暂停,
					Sort = ConstValues.DefaultSort,
					IsLocked = false,
					PasswordFailed = ConstValues.intZero,
					Language = language,
					Creator = model.UserName?.Trim(),
					CreateIP = Utility.GetRealIP(),
					CreateDate = DateTime.Now,
					HasSend = false,
				};
				DbContext.SysUserMaster.Add(sysUserMaster);
				
				if (Request.Cookies["_culture"] != null && Request.Cookies["_culture"].Value == ConstValues.Language.En)
				{
					if (model.Country != 7)
					{
						sysUserMaster.HasUpdate = true;
					}
					else
					{
						var sysUserMasterEn = new SysUserMasterEn
						{
							ID = Utility.GetTableId(ConstValues.TableName.SysUserMasterEn),
							FullName = Utility.SetFullName(model.FamilyName?.Trim(), model.FirstName?.Trim(), ConstValues.Language.En),
							FamilyName = model.FamilyName?.Trim(),
							FirstName = model.FirstName?.Trim(),
							Call = model.Call,
							Address = model.Address?.Trim(),
							Affiliation = model.Affiliation?.Trim(),
							Department = model.Department?.Trim(),
							CV = model.CV?.Trim(),

							UserName = sysUserMaster.UserName,
							Mail = sysUserMaster.Mail,
							Gender = sysUserMaster.Gender,
							Degree = sysUserMaster.Degree,
							Country = sysUserMaster.Country,
							StateStr = sysUserMaster.StateStr,
							CityStr = sysUserMaster.CityStr,
							Mobile = sysUserMaster.Mobile,
							Telephone = sysUserMaster.Telephone,
							Career = career,
							OcisCode = ocisCode,
							HasUpdate = false,
							Status = ConstValues.Status.正常,
							Sort = ConstValues.DefaultSort,
							CreateDate = DateTime.Now,
							Creator = model.UserName?.Trim(),
						};
						DbContext.SysUserMasterEn.Add(sysUserMasterEn);

						sysUserMaster.Call = null;
					}
				}
				else
				{
					if (model.Country == 7)
					{
						sysUserMaster.HasUpdate = true;
					}

					if (model.SaveEnInfo?.Trim() == ConstValues.SaveEnInfo)
					{
						var sysUserMasterEn = new SysUserMasterEn
						{
							ID = Utility.GetTableId(ConstValues.TableName.SysUserMasterEn),
							FullName = Utility.SetFullName(model.FamilyNameEN?.Trim(), model.FirstNameEN?.Trim(), ConstValues.Language.En),
							FamilyName = model.FamilyNameEN?.Trim(),
							FirstName = model.FirstNameEN?.Trim(),
							Call = model.CallEN,
							Address = model.AddressEN?.Trim(),
							Affiliation = model.AffiliationEN?.Trim(),
							Department = model.DepartmentEN?.Trim(),
							CV = model.CVEN?.Trim(),

							UserName = sysUserMaster.UserName,
							Mail = sysUserMaster.Mail,
							Gender = sysUserMaster.Gender,
							Degree = sysUserMaster.Degree,
							Country = sysUserMaster.Country,
							StateStr = sysUserMaster.StateStr,
							CityStr = sysUserMaster.CityStr,
							Mobile = sysUserMaster.Mobile,
							Telephone = sysUserMaster.Telephone,
							Career = career,
							OcisCode = ocisCode,
							HasUpdate = true,
							Status = ConstValues.Status.正常,
							Sort = ConstValues.DefaultSort,
							CreateDate = DateTime.Now,
							Creator = model.UserName?.Trim(),
						};
						DbContext.SysUserMasterEn.Add(sysUserMasterEn);
					}
				}

				await DbContext.SaveChangesAsync();
				transaction.Commit();
			}

			var smtpServer = ConstValues.SmtpServer;
			var mailAddress = ConstValues.MailAddress;
			var password = ConstValues.MailPassword;

			var mailServer = await DbContext.SysMailServerMaster.AsNoTracking()
					.OrderBy(x => x.Sort)
					.ThenByDescending(x => x.UpdateDate)
					.FirstOrDefaultAsync(x => x.Status == ConstValues.Status.正常);

			if (mailServer != null)
			{
				smtpServer = mailServer.MailServer;
				mailAddress = mailServer.Mail;
				password = mailServer.Password;
			}

			MailSender sender = new MailSender(smtpServer);
			MailAddress from = new MailAddress(mailAddress);
			MailAddress to = new MailAddress(model.Mail);

			MailMessage message = Utility.GetMailContent(new MailModel
			{
				MailRemark = ConstValues.MailSubject.系统注册,
				Language = Request.Cookies["_culture"] != null && Request.Cookies["_culture"].Value == ConstValues.Language.En ? ConstValues.Language.En : ConstValues.Language.Cn,
				ActiveUrl = ConstValues.SystemWeb + "/Account/Activate/" + newId,
				ActiveUrlTxt = ConstValues.SystemWeb + "/Account/Activate/" + newId,
			});
			message.To.Add(to);

			var mailTask = Task.Run(() =>
			{
				sender.SendMail(from, message, password);
			});

			return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessRegister), JsonRequestBehavior.AllowGet);
		}

		[HttpPost]
		public ActionResult SetCulture(string culture)
		{
			culture = CultureHelper.GetImplementedCulture(culture);
			HttpCookie cookie = Request.Cookies["_culture"];
			if (cookie != null)
			{
				cookie.Expires = DateTime.Now.AddDays(-1);
				cookie = new HttpCookie("_culture");
				cookie.Value = culture;
				cookie.Expires = DateTime.Now.AddYears(1);
			}
			else
			{
				cookie = new HttpCookie("_culture");
				cookie.Value = culture;
				cookie.Expires = DateTime.Now.AddYears(1);
			}
			Response.Cookies.Add(cookie);
			return RedirectToAction(nameof(RegisterController.Index), nameof(RegisterController).GetControllerName());
		}
	}
}